//
//  LoopOAuthViewController.swift
//  LoopWeibo
//
//  Created by loop安 on 2016/12/9.
//  Copyright © 2016年 loop. All rights reserved.
//

import UIKit
import SVProgressHUD

let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")

class LoopOAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    override func loadView() {
        super.loadView()
        self.view = webView
        webView.delegate = self
    }
    
    var dismissLogin:(()->())?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //手写控制器的背景色是透明的
        //不设置背景色,控制器modal出来是,只有控制器在移动
        view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", normalColor: #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1), highLightedColor: #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1), target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "后门",  normalColor: #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1), highLightedColor: #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1), target: self, action: #selector(pressAccount))
        
        loadOAueth()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    //webView加载页面
    private func loadOAueth(){
        //https://open.weibo.cn/oauth2/authorize?client_id=106804101&redirect_uri=http://www.weibo.com/u/1880956473/home?wvr=5
        let urlString = "https://open.weibo.cn/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = URL(string: urlString)
        let req = URLRequest(url: url!)
        webView.loadRequest(req)
        
    }
    
    
    //barbutton的点击事件
    @objc private func close(){
        self.dismiss(animated: true, completion: nil)
    }

    @objc private func pressAccount(){
        //OC调用JS,自动输入账号密码
        //调试结束,记得删除
        //document.getElementById('userId').value = '13062761471'
        //document.getElementById('passwd').value = 'loop0810'
        let jsString = "document.getElementById('userId').value = '13062761471',document.getElementById('passwd').value = 'loop0810'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
}


extension LoopOAuthViewController:UIWebViewDelegate{
    
    func webViewDidStartLoad(_ webView: UIWebView){
//        print(#function)
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView){
//        print(#function)
        SVProgressHUD.dismiss()
    }

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        let requestString = request.url?.absoluteString ?? ""
        let flag = "code="
        print(requestString)
        if requestString.contains(flag){
            let url = request.url?.query ?? ""
            let code = (url as NSString).substring(from: flag.characters.count)
        
//            loadUserToken(code: code)
            LoopUserAccountViewModel.shared.loadUserToken(code: code, finish: { (isSuccess:Bool) in
                if !isSuccess{
                SVProgressHUD.showError(withStatus: errorTip)
                }
                print("登陆成功")
//                let welcome = LoopWelcomeViewController()
//                welcome.dismissOAuth = {
//                    self.dismissLogin?()
//                }
//                UIApplication.shared.keyWindow?.rootViewController = LoopWelcomeViewController()
                NotificationCenter.default.post(name: Notification.Name(kChangeRootController), object: "Welcome")
                
            })
            return false
        }
    return true
    }
    
    
    ///以下代码抽出到viewModel中
    
//    private func loadUserToken(code:String){
//        
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        let parameters = ["client_id" : client_id,
//                          "client_secret" : client_secret,
//                          "grant_type" : "authorization_code",
//                          "code" : code,
//                          "redirect_uri" : redirect_uri]
//        LoopNetWorkManager.shared.request(HTTPMethod: .POST, urlString: urlString, parameters: parameters) { (responseObject, error) in
//            if error != nil{
//                SVProgressHUD.showError(withStatus: errorTip)
//                return
//            }
//            //走到这里程序一定是成功的
////            print(responseObject)
//            self.loadUserInfo(dic: responseObject as! [String : Any])
//        }
//    }
//    
//    private func loadUserInfo(dic:[String : Any]){
////        print("123")
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        let access_token = dic["access_token"]
//        let uid = dic["uid"]
//        let parameters = ["access_token" : access_token,
//                          "uid" : uid]
//        print(parameters)
//        LoopNetWorkManager.shared.request(HTTPMethod: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
//            if error != nil{
//                SVProgressHUD.showError(withStatus: errorTip)
//                return
//            }
////            print(responseObject)
//            
//            //将返回的数据转换成字典
//            var userInfo = responseObject as! [String : Any]
//            
//            //由于access_token在传入的dic中,所以我们需要将两个字典合并
//            for (key,value) in dic {
//                userInfo[key] = value
//            }
//            
//            //归档,将数据存储到本地
//            //创建模型数据
//            let userAccount = LoopUserAccount(dic: userInfo)
//            
//            self.saveUserInfo(userAccount: userAccount)
//        }
//    
//    }
//    
//    //归档方法
//    private func saveUserInfo(userAccount:LoopUserAccount){
//        //得到的路径其实是一个数组,所以需要加上一个last
//        //由于需要拼接文件路径,所以需要将路径转为NSString
//        //使用默认转换的前提,被转换类型不能为可选类型
//        
//        NSKeyedArchiver.archiveRootObject(userAccount, toFile: path)
//    }
//    
//    //解档方法
//    private func loadUserInfo()->LoopUserAccount?{
//    
//        let account = NSKeyedUnarchiver.unarchiveObject(withFile: path)
//        
//        //判断时候可以转换为LoopUserAccount类型,可以返回,否则返回一个空值
//        if let userAccount = account as? LoopUserAccount{
//        
//            return userAccount
//        }
//    
//        return nil
//    }
    
}


